import {
  Body,
  Controller,
  Get,
  Post,
  UploadedFile,
  UseInterceptors
} from '@nestjs/common'
import { AppService } from './app.service'
import { FileInterceptor } from '@nestjs/platform-express'
import { diskStorage } from 'multer'
import { extname, join } from 'path'

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Get()
  getHello(): string {
    return this.appService.getHello()
  }

  @Post('ablum')
  @UseInterceptors(
    FileInterceptor('file', {
      storage: diskStorage({
        destination: (_, file, cb) => {
          cb(null, join(__dirname, '..', '..', 'images'))
        },
        filename: (_, file, cb) => {
          cb(null, `${new Date().getTime() + extname(file.originalname)}`)
        }
      })
    })
  )
  async upload(@UploadedFile() file) {
    return file
  }

  @Post('upload')
  @UseInterceptors(FileInterceptor('file'))
  async uploadFile(@UploadedFile() file, @Body('directory') directory: string) {
    const filePath = await this.appService.uploadFile(file, directory)

    return { filePath }
  }
}
